package service

import (
	"admin-system-go/model"
	"admin-system-go/model/do"
	"admin-system-go/model/dto"
	"admin-system-go/repository"
)

type PermissionService interface {
	QueryPermission(dto dto.PermissionQueryDTO) model.ResponseEntity
	CreatePermission(dto dto.PermissionBaseDTO) model.ResponseEntity
	DelPermission(dto dto.PermissionDelDTO) model.ResponseEntity
	UpdatePermission(updateDTO dto.PermissionUpdateDTO) model.ResponseEntity
}

type permissionServiceImpl struct{}

func (permissionService permissionServiceImpl) QueryPermission(queryDto dto.PermissionQueryDTO) model.ResponseEntity {
	var permission do.Permission
	_ = repository.Copy(queryDto, &permission)
	var permissions []do.Permission
	pageSize := queryDto.PageSize
	pageNo := queryDto.PageNo
	var total int64
	_ = repository.GetDb().Where(&permission).Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&permissions)
	var result = make([]dto.PermissionQueryDTO, len(permissions))
	if len(permissions) != 0 {
		_ = repository.GetDb().Model(&do.Permission{}).Where(&permission).Count(&total)
	}
	_ = repository.CopySlice(permissions, result)
	return model.PageEntityModel(result, &model.PageInfo{
		Total:    total,
		PageSize: pageSize,
		PageNo:   pageNo,
	})
}

func (permissionService permissionServiceImpl) CreatePermission(createDto dto.PermissionBaseDTO) model.ResponseEntity {
	var permission do.Permission
	_ = repository.Copy(createDto, &permission)
	tx := repository.GetDb().Where(&do.Permission{Name: createDto.Name}).Find(&permission)
	if tx.RowsAffected > 0 {
		return model.FailEntityModel("权限已经存在")
	}
	tx = repository.GetDb().Create(&permission)
	return model.BoolEntityModel(tx.RowsAffected == 1, tx.Error)
}

func (permissionService permissionServiceImpl) DelPermission(delDto dto.PermissionDelDTO) model.ResponseEntity {
	tx := repository.GetDb().Delete(&do.Permission{}, delDto.PermissionIds)
	return model.BoolEntityModel(tx.RowsAffected >= 1, tx.Error)
}

func (permissionService permissionServiceImpl) UpdatePermission(updateDTO dto.PermissionUpdateDTO) model.ResponseEntity {
	var oldPermission do.Permission = do.Permission{Model: model.Model{Id: updateDTO.Id}}
	tx := repository.GetDb().Model(&oldPermission).Find(&oldPermission)
	if tx.RowsAffected == 0 {
		return model.FailEntityModel("权限不存在")
	}
	_ = repository.Copy(updateDTO, &oldPermission)
	tx = repository.GetDb().Model(&oldPermission).Save(&oldPermission)
	if tx.Error == nil {
		return model.SuccessEntityModel(true)
	} else {
		return model.FailEntityModel("更新失败")
	}
}
